package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.dao.CheckItemDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = CheckGroupService.class)
//涉及多表，使用事务管理
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    private CheckGroupDao checkGroupDao;
    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {

        checkGroupDao.add(checkGroup);
        addGroupAndItem(checkGroup.getId(),checkitemIds);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<CheckGroup> page = checkGroupDao.selectByCondition(queryPageBean.getQueryString());
        List<CheckGroup> checkGroups = page.getResult();
        long total = page.getTotal();
        return  new PageResult(total,checkGroups);
    }

    @Override
    public CheckGroup findById(int id) {
        return checkGroupDao.findById(id);
    }

    @Override
    public List<Integer> findItemById(int id) {
        return checkGroupDao.findItemById(id);
    }

    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkGroupDao.edit(checkGroup);
//      清理原有关系
        checkGroupDao.deleteCheckGroup(checkGroup.getId());
//      添加新增关系
        addGroupAndItem(checkGroup.getId(),checkitemIds);

    }

    @Override
    public void deleteById(int id) {
        checkGroupDao.deleteCheckGroup(id);
        checkGroupDao.deleteByIds(id);
    }

    @Override
    public List<CheckGroup> findAll() {
       return checkGroupDao.findAll();
    }

    private void addGroupAndItem(int id,Integer[] checkitemIds){

        if (checkitemIds!=null&&checkitemIds.length>0){
           for (Integer checkitemId : checkitemIds) {
            Map<String, Integer> map = new HashMap<>();
            map.put("itemId", checkitemId);
            map.put("groupId", id);
            checkGroupDao.addGroupAndItem(map);
           }
        }
    }

}
